﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TireBias.Models;
using WinNemoLib;

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using System.Net;

namespace TireBias.Controllers
{
    public class BiasHead_KANBANController : Controller
    {
        //
        // GET: /BiasHead_KANBAN/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult USE_KANBAN(string seq, string biasno, string shift)
        {
            ViewBag.Full = "F";
    
           SessionBag.Current.biasno = biasno;
           SessionBag.Current.shift = shift;
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
            BIASPLANModel mdSearch = new BIASPLANModel();

            list = mdSearch.GET_TOPCORDPLN_ACT(seqs[0], "1", biasno, "", seqs[1],false,false);
            if (list.Count <= 0)
            {
                return View(new BIASPLANModel.BIASPLAN_DS());
            }
            return View(list[0]);
        }

        public JsonResult Get_Value(string seq, string biasno, string shift)
        {
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

            List<BIASSUBPlanModel.BIASSUBPlan_DS> list = new List<BIASSUBPlanModel.BIASSUBPlan_DS>();
            list = mdSearch.SEL_HEAD_NOFIN(biasno, seqs[0], seqs[1]);

            TopCordBomModel chk = new TopCordBomModel();
       

            if (list.Count <= 0)
                return Json(new { success = 0, message = "ไม่พบข้อมูล" });
            else
                return Json(new { success = 1, message = "", ply1 = list[0]._Ply1, ply2 = list[0]._Ply2, subItem = list[0]._sitemno, aPly1 = list[0]._angPly1, aPly2 = list[0]._angPly2, w1 = list[0]._widthPly1, w2 = list[0]._widthPly2 });
        }

        public ActionResult RollBack_Data(string seq, string biasno, string shift, string subItem,string  sample="")
        {
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();
                string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                if (mdSearch.DEL_SUB_BIAS(cnn, seqs[0], biasno, seqs[1], subItem))
                {
                    cnn.CommitTransaction();
                }
                else cnn.RollbackTransaction();
            }
            
            if (StrUtil.IsNotEmpty(sample)) {
                return RedirectToAction("New_Sample", "NewSample", new { seq = seq });            
            }
            return RedirectToAction("Use_KANBAN", "BiasHead", new { seq = seq, biasno = biasno, shift = shift });
        }

        public JsonResult Run_TireSTD(List<BIASSUBPlanModel.BIASSUBPlan_DS> thedata)
        {
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
       
            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();
               
                if (mdSearch.UPDATE_SUB_STATUS_BIAS(cnn, thedata[0]))
                {  
                    cnn.CommitTransaction();
                 

                    return Json(new { success = 1, message = "" });
                  
                }
                else
                { 
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });                   
                }
            }

        }


        public JsonResult UPDATE_ANG(List<BIASSUBPlanModel.BIASSUBPlan_DS> thedata)
        {
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();

                if (mdSearch.UPDATE_SUB_STATUS_BIAS(cnn, thedata[0],"AN"))
                {
                    cnn.CommitTransaction();
                    return Json(new { success = 1, message = "" });

                }
                else
                {
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
                }
            }

        }

        public JsonResult FINIS_TireSTD(List<BIASSUBPlanModel.BIASSUBPlan_DS> thedata)
        {
            KANBANPlanModel mdSearch = new KANBANPlanModel();
            BIASSUBPlanModel mdAng = new BIASSUBPlanModel();

            using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
            {
                cnn.Open();
                cnn.BeginTransaction();

                if (!mdAng.UPDATE_SUB_STATUS_BIAS(cnn, thedata[0], "AN"))
                {
                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });

                }

                if (! mdSearch.UPDATE_STATUS_BIAS(cnn, thedata[0]))
                {                 

                    cnn.RollbackTransaction();
                    return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
                }
                cnn.CommitTransaction();
               string showDelay = "";
                if (StrUtil.IsNotEmpty(thedata[0]._size))
                {
                    List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
                    BIASPLANModel getNext = new BIASPLANModel();
                    list = getNext.GET_TOPCORDPLN_ACT("", "", thedata[0]._biasno, "L", "", true);
                    if (list.Count > 0) if (list[0]._Size.Trim() != thedata[0]._size.Trim()) showDelay = "1";

                }

                return Json(new { success = 1, message = "",delays=showDelay });
            }

        }

        public JsonResult GET_TireSTD(string code, string sizes, string forming,string ply)
        {

            TopCordBomModel chk = new TopCordBomModel();
            List<TopCordBomModel.TIRESTDS_DS> list;
            list = chk.SEL_TOPCORDBOM(code, sizes, forming,ply);
            return Json(list);

        }

        [Authorize]
        /// <summary>
        /// getPDF Standard
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="biasno"></param>
        /// <param name="shift"></param>
        /// <param name="subItem"></param>
        /// <returns></returns>
        /// 
        public ActionResult GET_PDF_STD(string seq, string biasno, string shift,string subItem,string Information="")
        {
            ViewBag.Full = "F";
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);          

            List<KANBANPlanModel.KANBANPlan_DS> list = new List<KANBANPlanModel.KANBANPlan_DS>();
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();
           
            list = mdSearch.GET_KANBANPLAN_SUB(biasno, seqs[0], seqs[1], subItem);

            if (StrUtil.IsNotEmpty(list[0]._angPly1))
            {
                List<BIASPLANModel.BIASPLAN_DS> ds = new List<BIASPLANModel.BIASPLAN_DS>();
                BIASPLANModel getRes = new BIASPLANModel();

                ds = getRes.GET_TOPCORDPLN_ACT(list[0]._plandt, "1", list[0]._biasno, "", list[0]._itemno);
                if (ds.Count > 0)
                {
                    // เหลือให้ new ply
                    BIASPLANModel.BIASPLAN_DS data = ds[0];
                    int res = Convert.ToInt32(data.cP1) + Convert.ToInt32(data.cP2) + Convert.ToInt32(data.cP3) + Convert.ToInt32(data.cP4);
                    if (res > 0)
                    {
                        return RedirectToAction("Use_KANBAN","BiasHead", new { seq = list[0]._plandt + "-" + list[0]._itemno, biasno = list[0]._biasno, shift = list[0]._shift });
                    }
                }
               
            }

            list[0]._Information = Information;
            return View(list[0]);            
        }

        public ActionResult GetPDF(string code, string sizes, string forming)
        {
            try
            {
                TopCordBomModel inf = new TopCordBomModel();
                List<TopCordBomModel.TIRESTDS_DS> infList = inf.SEL_TOPCORDBOM(code, sizes, forming);

                var address = Dns.GetHostAddresses(Nemo.GetINI("File", "DNS"))[0];
                string path = @"\\" + address + @"\" + Nemo.GetINI("File", "FilePath");
                string nm = infList[0]._Filenm;
                string sub = infList[0]._SubFd;

                if (!WinNemoLib.DriveMapper.GetConnected(null, path))
                {
                    DriveMapper.MapDrive(null, path, Nemo.GetINI("File", "USER"), Nemo.GetINI("File", "PWD"));
                }
                string file = path + @"\" + sub + @"\" + nm;
                FileInfo infile = new FileInfo(file);
                if (!infile.Exists)
                {

                    MemoryStream workStream = new MemoryStream();
                    Document document = new Document();
                    PdfWriter.GetInstance(document, workStream).CloseStream = false;

                    document.Open();
                    document.Add(new Paragraph("Cannot Open File !!!" + nm));

                    document.Close();

                    byte[] byteInfo = workStream.ToArray();
                    workStream.Write(byteInfo, 0, byteInfo.Length);
                    workStream.Position = 0;

                    return new FileStreamResult(workStream, "application/pdf");
                }

                return new FileContentResult(System.IO.File.ReadAllBytes(file), "application/pdf");
            }
            catch (Exception)
            {
                
                throw;
            }
         

        }
        /// <summary>
        /// GET PDF INF
        /// </summary>
        /// <param name="seq"></param>
        /// <param name="biasno"></param>
        /// <param name="shift"></param>
        /// <param name="subItem"></param>
        /// <returns></returns>
        public ActionResult GET_PDF_INF(string seq, string biasno, string shift, string subItem)
        {
            ViewBag.Full = "F";
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

            List<KANBANPlanModel.KANBANPlan_DS> list = new List<KANBANPlanModel.KANBANPlan_DS>();
            BIASSUBPlanModel mdSearch = new BIASSUBPlanModel();

            list = mdSearch.GET_KANBANPLAN_SUB(biasno, seqs[0], seqs[1], subItem);
                 TopCordBomModel inf = new TopCordBomModel();
            List<TopCordBomModel.TIRESTDS_DS> infList = inf.SEL_TOPCORDBOM_INF(list[0]._topcrdcd, list[0]._sizes, list[0]._forming);

            if (infList.Count <= 0)
            {
                return RedirectToAction("GET_PDF_STD", new { seq = seq, biasno = biasno, shift = shift, subItem = subItem });
            }


            return View(list[0]);


        }

        public ActionResult GetPDF_INF(string code,string sizes,string forming)
        {
            TopCordBomModel inf = new TopCordBomModel();
            List<TopCordBomModel.TIRESTDS_DS> infList = inf.SEL_TOPCORDBOM_INF(code, sizes, forming);

            if (infList.Count <= 0)
            {
                RedirectToAction("GetPDF", new { code = code, sizes = sizes, forming = forming });
            }

            var address = Dns.GetHostAddresses(Nemo.GetINI("File", "DNS"))[0];
            string path = @"\\" + address + @"\" + Nemo.GetINI("File", "FilePath");
            string nm = infList[0]._Filenm;
            string sub = infList[0]._SubFd;

            if (!WinNemoLib.DriveMapper.GetConnected(null, path))
            {
                DriveMapper.MapDrive(null, path, Nemo.GetINI("File", "USER"), Nemo.GetINI("File", "PWD"));
            }
            string file = path + @"\" + sub + @"\" + nm;
            FileInfo infile = new FileInfo(file);
            if (!infile.Exists)
            {

                MemoryStream workStream = new MemoryStream();
                Document document = new Document();
                PdfWriter.GetInstance(document, workStream).CloseStream = false;

                document.Open();
                document.Add(new Paragraph("Cannot Open File !!!"+ nm));

                document.Close();

                byte[] byteInfo = workStream.ToArray();
                workStream.Write(byteInfo, 0, byteInfo.Length);
                workStream.Position = 0;

                return new FileStreamResult(workStream, "application/pdf");
            }
            return new FileContentResult(System.IO.File.ReadAllBytes(file), "application/pdf");             

        }

        public JsonResult GET_NOTValue(string seq, string biasno, string shift)
        {
         
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            List<BIASPLANModel.BIASPLAN_DS> list = new List<BIASPLANModel.BIASPLAN_DS>();
            BIASPLANModel mdSearch = new BIASPLANModel();

            list = mdSearch.GET_TOPCORDPLN_ACT(seqs[0],"1", SessionBag.Current.biasno, "", seqs[1]);
            if (list.Count <= 0)
            {
                return Json(new { success = 1 });
            }
            BIASPLANModel.BIASPLAN_DS data = list[0];
            int res = Convert.ToInt32(data.cP1) + Convert.ToInt32(data.cP2) + Convert.ToInt32(data.cP3) + Convert.ToInt32(data.cP4);
            if (res > 0)
            {
                return Json(new { success = 1 });
            }
            return Json(new { success = 0 });
        }


     
    }
}
